package com.tzbank.voice.esb.provide;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.boot.web.filter.OrderedHiddenHttpMethodFilter;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.HiddenHttpMethodFilter;
import com.dcfs.esb.server.ESBServer;

@Configuration
public class EsbProvide {

	@Bean
	public ServletRegistrationBean esbServletRegistration() {
		ServletRegistrationBean registration = new ServletRegistrationBean(new ESBServer());
		registration.addInitParameter("EAI_HOME", "/home/admin/tzbank/voice");
		registration.addUrlMappings("/bisVoice");
		registration.setLoadOnStartup(2);
		registration.setName("bisVoice");
		return registration;
	}

	@Bean
	public HiddenHttpMethodFilter hiddenHttpMethodFilter() {
		return new OrderedHiddenHttpMethodFilter() {
			@Override
			protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
					FilterChain filterChain) throws IOException, ServletException {

				MultiReadHttpServletRequest multiReadRequest = new MultiReadHttpServletRequest(
						(HttpServletRequest) request);
				boolean isMultipart = ServletFileUpload.isMultipartContent(multiReadRequest);
				if (!isMultipart && multiReadRequest.getMethod().toUpperCase().equals("POST")) {
					String c_request_body = getRequestPayload(multiReadRequest);
					multiReadRequest.setAttribute("_request_body", c_request_body);
				}

				multiReadRequest.rebuildParams();
				filterChain.doFilter(multiReadRequest, response);
			}

		};
	}

	public String getRequestPayload(HttpServletRequest req) {
		StringBuilder sb = new StringBuilder();
		try {
			BufferedReader reader = req.getReader();
			char[] buff = new char[1024];
			int len;
			while ((len = reader.read(buff)) != -1) {
				sb.append(buff, 0, len);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return sb.toString();
	}
}
